package com.itheima.my_reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.my_reggie.common.Result;
import com.itheima.my_reggie.pojo.User;
import com.itheima.my_reggie.service.IUserService;
import com.itheima.my_reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

//   调用手机验证码的功能
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
//            session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return Result.success("手机验证码短信发送成功");
        }
        return Result.error("短信发送失败");
    }
//移动端的登录功能
    @PostMapping ("/login")
    public Result<User> userLogin(@RequestBody Map map, HttpSession session){
        log.info("用户登录，{}",map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String userCode = map.get("code").toString();
        //从Session中获取保存的验证码
//        Object sysCode = session.getAttribute(phone);
//        从redis中获取验证码信息
        String sysCode = (String) redisTemplate.opsForValue().get(phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if(sysCode != null && sysCode.equals(userCode)){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(queryWrapper);
            if(user == null){
                //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
//            删除redis中的验证码
            redisTemplate.delete(phone);
            return Result.success(user);
        }
        return Result.error("登录失败");
    }



//    移动端的退出功能
@PostMapping("/logout")
public Result<String> userLogOut(HttpServletRequest request){
//      重置session中的数据
    request.getSession().removeAttribute("user");
//      提示退出成功
    return Result.success("退出成功");
}

}
